package com.example.apipassenger.interceptor;


import com.example.internalcommon.constant.TokenConstants;
import com.example.internalcommon.dto.ResponseResult;
import com.example.internalcommon.dto.TokenResult;
import com.example.internalcommon.util.JwtUtils;
import com.example.internalcommon.util.RedisPrefixUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author lyra
 * @Date 2023/4/6 13:37
 **/
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * JwtInterceptor会在bean初始化之前初始化
     * 所以需要在拦截器初始化之前对该bean进行初始化
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 7.拦截器
     * 判断客户端是否携带token,如果有,则通过JWT库的方法解析token中的的值
     * 如果解析
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;

        String resultString = "";

        String token = request.getHeader("Authorization");

        // 解析token
        TokenResult tokenResult = JwtUtils.checkToken(token);

        /**
         * 8.通过存储的token进行token校验
         */
        if (tokenResult == null){
            resultString = "access token invalid";
            result = false;
        }else {
            // 拼接key
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();

            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
            // 从redis中去除token
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
            if ((StringUtils.isBlank(tokenRedis)) || (!token.trim().equals(tokenRedis.trim()))) {
                resultString = "access token invalid";
                result = false;
            }
        }
        /*else {
                // 比较我们传入的 token 和 redis中的token 是否相等
                if (){
                    resultString = "token invalid";
                    result = false;
                }
            }*/

        if (!result){                               // 拦截器不放行 , 则将错误打印到控制台
            PrintWriter out = response.getWriter();
            out.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
        }

        return result;
    }
}
